package com.example.client_anna.module.ui;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.client_anna.R;
import com.example.client_anna.module.branch_home.HomeOrderActivity;
import com.example.client_anna.network.okhttp3.HttpUtilImpl;
import com.example.client_anna.network.okhttp3.RequestUrl;
import com.example.client_anna.network.room.entity.Goods;
import com.example.client_anna.util.adapter.ExploreAdapter;
import com.example.client_anna.util.adapter.OrderOuterAdapter;
import com.example.client_anna.util.entity.HomeShopGroupItem;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * @author cy
 * @email 272884043@qq.com
 * @date 2021/10/19
 */
public class OrderFragment extends Fragment {

    private static final String TAG = "OrderFragment";

    private static final int ORDER_INTERFACE_SUCCESS = 200;

    private View rootView;
    private RecyclerView recyclerView;

    private OrderOuterAdapter orderOuterAdapter;

    private List<JSONObject> list = new ArrayList<>();

    //用户登录信息，用户id
    private static String user_id;

    @Override
    public void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //访问存储在本地的文件，通过键值对的方式读取想要的信息出来
        SharedPreferences preferences =getActivity().getSharedPreferences("UserInfo", Context.MODE_PRIVATE);
        //读取key为user_id中的值，如果没有数据就赋值0给key
        //String.valueOf强类型转换
        user_id = preferences.getString("user_id","0");

    }

    @Override
    public void onActivityCreated(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //实例化SmartRefreshLayout控件
        RefreshLayout refreshLayout = (RefreshLayout) getActivity().
                findViewById(R.id.order_refreshLayout);
        //SmartRefreshLayout事件回调方法
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                Order_Interface_Okhttp3();
                //数据刷新完结束事件
                refreshLayout.finishRefresh(true);
            }
        });
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        if(rootView==null){
            rootView = inflater.inflate(R.layout.activity_order_fragment,container,false);
            recyclerView = rootView.findViewById(R.id.order_recycler_outer_view);
            //取消动画效果
            ((DefaultItemAnimator) recyclerView.getItemAnimator())
                    .setSupportsChangeAnimations(false);
            //不显示执行动画
            recyclerView.setItemAnimator(null);
            Order_Interface_Okhttp3();
        }
        return rootView;
    }

    private void Order_Interface_Okhttp3() {
        Log.d(TAG,"user_id "+user_id);

        if(!"0".equals(user_id)){
            //具体请求对象
            String info = "order_user_info";
            //链接的地址
            String address = RequestUrl.getUrl() + "order" + "?" + "request=" + info;
            //创建RequestBody请求体,用于数据的提交
            RequestBody requestBody = new FormBody.Builder()
                    .add("uid",user_id)
                    .build();
            HttpUtilImpl.sendOKHttpRequest(address, requestBody, new okhttp3.Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    //onFailure方法用于网络请求失败后执行的语句
                    //取消请求的判断，true用户主动关闭活动页面，false超时或者网络出错
                    if (e.toString().contains("closed")) {
                        //用户直接关闭页面后取消请求
                        call.cancel();
                    } else {
                        //网络不稳定，或者无网络
                        Message message = new Message();
                        message.what = 400;
                        handler.sendMessage(message);
                        //取消请求
                        call.cancel();
                    }
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    //onResponse方法用于接收访成功后回调后的操作
                    //得到response对象的具体内容
                    String orderInfo = response.body().string();
                    //数据处理
                    ParesJsonWithGSON_orderSub(orderInfo);
                }
            });

        }

    }

    private void ParesJsonWithGSON_orderSub(String jsonData){
        if(!(jsonData.isEmpty())){
            JSONObject jsonObject = new JSONObject();
            jsonObject = JSON.parseObject(jsonData);
            Gson gson = new Gson();

            if("success".equals(jsonObject.get("message").toString())){

                list.clear();
                list = gson.fromJson(jsonObject.get("data").toString(),new TypeToken<List<JSONObject>>(){}.getType());
                if (list!=null){
                    Log.d(TAG,"成功接收");

                    Message message = new Message();
                    message.what = ORDER_INTERFACE_SUCCESS;
                    handler.sendMessage(message);

                }


            }else if("fail".equals(jsonObject.get("message").toString())){

                Message message = new Message();
                message.what = ORDER_INTERFACE_SUCCESS;
                handler.sendMessage(message);

            }

        }

    }

    private Handler handler = new Handler(){

        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what){
                case OrderFragment.ORDER_INTERFACE_SUCCESS:
                    orderOuterAdapter = new OrderOuterAdapter(list);
                    //加载闪烁问题：添加标记tag,tag标记着每一张请求url的图片，加载的时候防止重新加载
                    //需要重写adapter的getItemId方法
                    orderOuterAdapter.setHasStableIds(true);
                    //适配器数据改变
                    orderOuterAdapter.notifyDataSetChanged();
                    //GridLayoutManager布局方式，参数1:Context，参数2:列数
                    GridLayoutManager layoutManager = new GridLayoutManager(getContext(),1);
                    recyclerView.removeAllViews();//移除所有item
                    //加载布局方式
                    recyclerView.setLayoutManager(layoutManager);
                    //recyclerView布局加载适配器
                    recyclerView.setAdapter(orderOuterAdapter);
                    break;
            }
        }
    };
    
}